# -*-coding:utf-8-*-

import json
from tornado.ioloop import IOLoop
from handlers.base import Mqtonado
import settings
from tests.configs import TEST_DEVICES
import time

DEVICE_ID = TEST_DEVICES[0]['device_id']
RPC_REQ_TOPIC = 't/d/%s/q/#' % DEVICE_ID
RPC_RES_TOPIC = 'f/d/%s/p/' % DEVICE_ID
WILL_TOPIC = 't/s/8/w/f/d/%s/n/offline' % DEVICE_ID
TOPIC_NOTIFY_ONLINE = 't/s/8/w/f/d/%s/n/online' % DEVICE_ID
TOPIC_NOTIFY_WPM_STAT = 't/s/8/w/f/d/%s/n/wpm_stat' % DEVICE_ID
TOPIC_NOTIFY_WPM_MISC = 't/s/8/w/f/d/%s/n/wpm_misc' % DEVICE_ID
TOPIC_NOTIFY_WPM_USAGE = 't/s/8/w/f/d/%s/n/wpm_usage' % DEVICE_ID

from bson.objectid import ObjectId

rid = str(ObjectId())
TOPIC_RDS_RES_WPM_QUOTA = 't/d/%s/p/%s' % (DEVICE_ID, rid)
TOPIC_RDS_REQ_WPM_QUOTA = 't/s/8/q/%s/%s/h/t/d/%s/p' % (rid, 'wpm_quota', DEVICE_ID)


def on_message(client, userdata, topic, payload):
    print '%s: %s' % (topic, payload)
    topic_splited = topic.split('/')
    if 'q' in topic_splited:
        req_id = topic_splited[-2]
        request = json.loads(payload)
        print 'request_name:' + topic_splited[-1]
        print 'request_id:' + req_id
        print request
        response = {
            'result': True,
            'error_code': 0,
            'error_message': 'ok',
        }
        client.publish(RPC_RES_TOPIC + req_id, json.dumps(response))
    elif 'p' in topic_splited:
        pass


def on_timeout(client):
    client.publish(TOPIC_RDS_REQ_WPM_QUOTA)


def main():
    client = Mqtonado(on_message, None)
    client.connect(settings.MQ_HOST, username=settings.MQ_USER, password=settings.MQ_PASS, will_topic=WILL_TOPIC)
    client.subscribe(RPC_REQ_TOPIC)
    # client.subscribe('t/d/%s/p/#' % DEVICE_ID)
    client.subscribe(TOPIC_RDS_RES_WPM_QUOTA)
    print TOPIC_RDS_RES_WPM_QUOTA
    client.publish(TOPIC_NOTIFY_ONLINE)

    wpm_stat = {
        "stat": 3,
        "otmp": 98,
        "itmp": 98,
        "otds": 0,
        "itds": 0,
    }
    client.publish(TOPIC_NOTIFY_WPM_STAT, json.dumps(wpm_stat))

    wpm_misc = {
        "ver": "0.1.2",
        "imsi": "460040889504426",
        "lbs": "0,0",
        "iccid": "898602B8191651468766",
        "imei": "862991528671420",
        "build": "20170801",
    }
    client.publish(TOPIC_NOTIFY_WPM_MISC, json.dumps(wpm_misc))

    wpm_usage = {
        "tp": 0,
        "tm": 5,
    }
    client.publish(TOPIC_NOTIFY_WPM_USAGE, json.dumps(wpm_usage))

    IOLoop.current().add_timeout(time.time() + 3, on_timeout, client)

    IOLoop.current().start()


if '__main__' == __name__:
    main()
